package com.yh.autobio.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.google.gson.Gson;
import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.api.ErrorHandler;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.base.BaseFragment;
import com.yh.autobio.common.ArithUtil;
import com.yh.autobio.common.FullyLinearLayoutManager;
import com.yh.autobio.common.PLog;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.common.TDevice;
import com.yh.autobio.common.Time;
import com.yh.autobio.common.UIHelper;
import com.yh.autobio.component.dialog.DialogHelp;
import com.yh.autobio.gddb.gbmanager.BackMatManager;
import com.yh.autobio.gddb.gbmanager.MatHeadManager;
import com.yh.autobio.gddb.gbmanager.MatHeadManager2;
import com.yh.autobio.gddb.gbmanager.MatManager;
import com.yh.autobio.gddb.gdbean.BackMatBean;
import com.yh.autobio.gddb.gdbean.MatBean;
import com.yh.autobio.gddb.gdbean.MatHead;
import com.yh.autobio.modules.adatper.ADDBackMatAdapter;
import com.yh.autobio.modules.bean.CM;
import com.yh.autobio.modules.bean.CustPhone;
import com.yh.autobio.modules.bean.MatSubBean;
import com.yh.autobio.modules.bean.Result;
import com.yh.autobio.modules.bean.SimpleBackPage;
import com.yh.autobio.modules.bean.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yh.autobio.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：john
 * <p>
 * 工程：FoodBarcode
 * <p>
 * 文件名：ADDBackMatFragment
 * <p>
 * 创建时间：2017.06.02.17:27
 * *****************************
 */
public class ADDBackMatFragment extends BaseFragment implements ADDBackMatAdapter.OnSaleAddAdapterListern {

    @InjectView(R.id.tv_date)
    TextView tvDate;
    @InjectView(R.id.ll_date)
    LinearLayout llDate;
    @InjectView(R.id.tv_gh_unit)
    TextView tvGhUnit;
    @InjectView(R.id.ll_gh_unit)
    LinearLayout llGhUnit;
    @InjectView(R.id.tv_sales_way)
    TextView tvSalesWay;
    @InjectView(R.id.ll_sales_way)
    LinearLayout llSalesWay;
    @InjectView(R.id.tv_bz)
    EditText tvBz;
    @InjectView(R.id.tv_pgno)
    TextView tvPgno;
    @InjectView(R.id.scrollView)
    ScrollView scrollView;
    @InjectView(R.id.tv_all_money)
    TextView tvAllMoney;
    @InjectView(R.id.ll_pgno)
    LinearLayout llPgno;
    @InjectView(R.id.tv_pgno_type)
    TextView tvPgnoType;
    @InjectView(R.id.ll_pgno_type)
    LinearLayout llPgnoType;
    @InjectView(R.id.tv_sale)
    TextView tvSale;
    @InjectView(R.id.ll_sale)
    LinearLayout llSale;
    @InjectView(R.id.tv_cust_phone)
    TextView tvCustPhone;
    @InjectView(R.id.ll_cust_phone)
    LinearLayout llCustPhone;
    @InjectView(R.id.tv_fh_warehouse)
    TextView tvFhWarehouse;
    @InjectView(R.id.ll_fh_warehouse)
    LinearLayout llFhWarehouse;
    @InjectView(R.id.ll_fj)
    LinearLayout llFj;
    @InjectView(R.id.recyclerview)
    RecyclerView mRecycleview;


    private ADDBackMatAdapter mAdapter;
    ArrayList<BackMatBean> checkedCKS;
    private MatHead head;
    private int position;
    private boolean isSave;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                User currentUser = AppContext.getInstance().getCurrentUser();
                if (currentUser == null) {
                    Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户为空，请重新登陆", Snackbar.LENGTH_SHORT).show();
                } else {
                    handleOtherText(message);
                }

            }
        }
    };
    private String mType;
    private ItemTouchHelper mItemTouchHelper;

    private void handleOtherText(String text) {

        if (dialog != null) {
            if (dialog.isShowing())
                dialog.dismiss();
        }
        //先去判断扫描的单号是否存在
        boolean matExist = MatManager.getInstance(mActivity).isMatExist(text, "0");
        if (matExist) {//存在
            //再去判断扫描的单号对应几个物料
            boolean mulMat1 = MatManager.getInstance(mActivity).isMulMat(text, "0");
            if (mulMat1) {//为true说明对应多个物料
                choiceSingleMat(text);
            } else {//走else说明只对应一个物料
                onlyMatInsert(text);
            }
        } else {//不存在
            Snackbar.make(mActivity.getWindow().getDecorView(), "出库单不匹配，请重新扫描或同步数据！", Snackbar.LENGTH_SHORT).show();
        }
    }


    public int getHeight(View view) {// 获得某组件的高度
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        return view.getMeasuredHeight();
    }

    //扫描条码只对应一个物料时的添加流程
    private void onlyMatInsert(String barcode) {


        //先判断已添加的中是否存在
        List<BackMatBean> listMatBean = mAdapter.getBackList();
        for (int i = 0; i < listMatBean.size(); i++) {
            BackMatBean matBean = listMatBean.get(i);
            String id = matBean.getBarcode();
            if (barcode.equals(id)) {
                double count = Double.parseDouble(matBean.getCount()) + 1;
                matBean.setCount(count + "");
//                BackMatManager.getInstance(mActivity).updateItemCount(matBean);
//                mAdapter.notifyItemInserted(0);
//                mAdapter.notifyDataSetChanged();

                final View childAt = mRecycleview.getChildAt(i);

                mAdapter.notifyItemChanged(i);
//                mRecycleview.setAdapter(mAdapter);

                final int finalI = i;
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
//                        PLog.i("lj","scrollViewHight="+getHeight(scrollView));
//                        PLog.i("lj","recycleviewHight="+getHeight(mRecycleview));
//                        PLog.i("lj","childAtHight="+getHeight(childAt));
//                        PLog.i("lj","childAtHight="+getHeight(childAt));
                        int i1 = (getHeight(scrollView) - getHeight(mRecycleview)) + getHeight(childAt) * finalI;
                        scrollView.smoothScrollTo(0, i1);
                    }
                });
//                layoutManager.scrollToPosition(i);
//                mRecycleview.scrollToPosition(i);
//                mAdapter.notifyItemChanged(i);





//                mRecycleview.setAdapter(mAdapter);
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//                    }
//                });
                return;
            }
        }

        MatBean matById = MatManager.getInstance(mActivity).getMatById(barcode, "0");
        BackMatBean backMatBean = new BackMatBean();

        backMatBean.setBarcode(matById.getBarcode());
        backMatBean.setUnitgroup_id(matById.getUnitgroup_id());
        backMatBean.setCredit(matById.getCredit());
        backMatBean.setDefunitId(matById.getDefunitId());
        backMatBean.setFtype(matById.getFtype());
        backMatBean.setId(matById.getId());
        backMatBean.setModel(matById.getModel());
        backMatBean.setName(matById.getName());
        backMatBean.setNumber(matById.getNumber());
        backMatBean.setSaleprice(Double.parseDouble(matById.getSaleprice()));
        backMatBean.setUnit_id(matById.getUnit_id());
        backMatBean.setUnitgroup_name(matById.getUnitgroup_name());
        backMatBean.setUnit_name(matById.getUnit_name());
        backMatBean.setCount("1");
        backMatBean.setBaseName(matById.getBaseName());
        backMatBean.setBaseunit(matById.getBaseunit());
        backMatBean.setReprice(matById.getReprice());
        backMatBean.setFDCStockName(head.getFhckName());
        backMatBean.setFDCStockID(head.getFhckId());
        backMatBean.setUnitType("0");//0代表baseName 1代表unit_name
        backMatBean.setUserName(AppContext.getInstance().getCurrentUser().getName());
//        BackMatManager.getInstance(mActivity).insertBackMat(backMatBean);//缓存
        checkedCKS.add(backMatBean);
        mAdapter = new ADDBackMatAdapter(mActivity, checkedCKS, this,mType);
        mRecycleview.setAdapter(mAdapter);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    private AlertDialog dialog;

    //从多个物料中选择一个加入缓存并刷新页面
    private void choiceSingleMat(String barcode) {

        //拿到该条码对应多个物料
        final ArrayList<MatBean> mulMat = MatManager.getInstance(mActivity).getMulMat(barcode, "0");
        String[] strings = new String[mulMat.size()];
        for (int i = 0; i < mulMat.size(); i++) {
            strings[i] = mulMat.get(i).getName();
        }
        dialog = DialogHelp.getSingleChoiceDialog(mActivity, "种类", strings, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String id = mulMat.get(i).getId();
                //先判断已添加的中是否存在
                ArrayList<BackMatBean> listMatBean = mAdapter.getBackList();
                for (int j = 0; j < listMatBean.size(); j++) {
                    BackMatBean matBeanCount = listMatBean.get(j);
                    String ids = matBeanCount.getId();
                    if (id.equals(ids)) {//已添加过同类型物料
                        int count = Integer.parseInt(listMatBean.get(j).getCount()) + 1;
                        matBeanCount.setCount(count + "");
//                        BackMatManager.getInstance(mActivity).updateItemCount(matBeanCount);

                        mAdapter.notifyItemChanged(j);
                        final View childAt = mRecycleview.getChildAt(j);
                        final int finalI = j;
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
//                                PLog.i("lj","scrollViewHight="+getHeight(scrollView));
//                                PLog.i("lj","recycleviewHight="+getHeight(mRecycleview));
//                                PLog.i("lj","childAtHight="+getHeight(childAt));
//                                PLog.i("lj","childAtHight="+getHeight(childAt));
                                int i1 = (getHeight(scrollView) - getHeight(mRecycleview)) + getHeight(childAt) * finalI;
                                scrollView.smoothScrollTo(0, i1);
                            }
                        });

                        mRecycleview.setAdapter(mAdapter);
//                        mHandler.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//                            }
//                        });
                        dialogInterface.dismiss();
                        return;
                    }
                }

                MatBean matById = MatManager.getInstance(mActivity).getMatById(id);
                BackMatBean backMatBean = new BackMatBean();

                backMatBean.setBarcode(matById.getBarcode());
                backMatBean.setUnitgroup_id(matById.getUnitgroup_id());
                backMatBean.setCredit(matById.getCredit());
                backMatBean.setDefunitId(matById.getDefunitId());
                backMatBean.setFtype(matById.getFtype());
                backMatBean.setId(matById.getId());
                backMatBean.setModel(matById.getModel());
                backMatBean.setName(matById.getName());
                backMatBean.setNumber(matById.getNumber());
                backMatBean.setSaleprice(Double.parseDouble(matById.getSaleprice()));
                backMatBean.setUnit_id(matById.getUnit_id());
                backMatBean.setUnitgroup_name(matById.getUnitgroup_name());
                backMatBean.setUnit_name(matById.getUnit_name());
                backMatBean.setCount("1");
                backMatBean.setBaseName(matById.getBaseName());
                backMatBean.setBaseunit(matById.getBaseunit());
                backMatBean.setReprice(matById.getReprice());
                backMatBean.setFDCStockName(head.getFhckName());
                backMatBean.setFDCStockID(head.getFhckId());
                backMatBean.setUnitType("0");//0代表baseName 1代表unit_name
                backMatBean.setUserName(AppContext.getInstance().getCurrentUser().getName());

//                BackMatManager.getInstance(mActivity).insertBackMat(backMatBean);//缓存
                checkedCKS.add(backMatBean);
                mAdapter = new ADDBackMatAdapter(mActivity, checkedCKS, ADDBackMatFragment.this,mType);
                mRecycleview.setAdapter(mAdapter);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
                dialogInterface.dismiss();
            }
        }).show();
//        mHandler.post(new Runnable() {
//            @Override
//            public void run() {
//                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
//            }
//        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_back_mat, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }


    @Override
    public void initView(View view) {
        super.initView(view);
        TDevice.hideSoftKeyboard(mActivity);
        setHasOptionsMenu(true);
        Bundle bundle = getArguments();
        mType = bundle.getString("TYPE");
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
        isSave = false;
        llGhUnit.setOnClickListener(this);
        llSalesWay.setOnClickListener(this);
        llFhWarehouse.setOnClickListener(this);
        llCustPhone.setOnClickListener(this);
        llSale.setOnClickListener(this);
        llDate.setOnClickListener(this);
        llPgno.setOnClickListener(this);
        llPgnoType.setOnClickListener(this);
        checkedCKS = new ArrayList<>();

        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(getContext());
        mRecycleview.setNestedScrollingEnabled(false);
        mAdapter = new ADDBackMatAdapter(mActivity, checkedCKS, this,mType);
        //关联ItemTouchHelper和RecyclerView
//        ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(mAdapter);
//        mItemTouchHelper = new ItemTouchHelper(callback);
//        mItemTouchHelper.attachToRecyclerView(mRecycleview);
        //设置布局管理器
        mRecycleview.setLayoutManager(linearLayoutManager);
    }

    @Override
    public void initData() {
        super.initData();
        String nowYMDHMSTime = Time.getNowYMDHMSTime();
        tvDate.setText(nowYMDHMSTime);
        this.head = new MatHead();
        head.setDate(nowYMDHMSTime);


        if ("show".equals(mType)) {
            String headid = getArguments().getString("ID");
            long Id = Long.parseLong(headid);
            head = MatHeadManager2.getInstance(mActivity).getHeadById(Id + "", "3");
            if (head != null) {
                tvDate.setText(head.getDate());
                tvSalesWay.setText(head.getXsfsName());
                tvGhUnit.setText(head.getGhdwName());
                tvPgno.setText(head.getHybName());
                tvSale.setText(head.getYwyName());
                tvCustPhone.setText(head.getKfdhName());
                tvFhWarehouse.setText(head.getFhckName());
                tvPgnoType.setText(head.getSklxName());
                tvBz.setText(head.getDesc());
            }
            List<BackMatBean> backMatsByHeadId = BackMatManager.getInstance(mActivity).getBackMatsByHeadId(Id);
            checkedCKS.addAll(backMatsByHeadId);
            mAdapter = new ADDBackMatAdapter(mActivity, checkedCKS, this,mType);
            mRecycleview.setAdapter(mAdapter);
        } else {
            mAdapter = new ADDBackMatAdapter(mActivity, checkedCKS, this,mType);
        }

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_pgno:
                bundle.putString("type", "hyb");
                UIHelper.showSimpleBackForResult(this, mActivity, 6, SimpleBackPage.CUST_PHEON, bundle, "货运部");
                break;
            case R.id.ll_gh_unit:
                bundle.putString("type", "ghdw");
                UIHelper.showSimpleBackForResult(this, mActivity, 1, SimpleBackPage.CUST_PHEON, bundle, "购货单位");
                break;
            case R.id.ll_sales_way:
                bundle.putString("type", "xsfs");
                UIHelper.showSimpleBackForResult(this, mActivity, 2, SimpleBackPage.CUST_PHEON, bundle, "销售方式");
                break;
            case R.id.ll_pgno_type:
                bundle.putString("type", "sklx");
                UIHelper.showSimpleBackForResult(this, mActivity, 3, SimpleBackPage.CUST_PHEON, bundle, "收款类型");
                break;
            case R.id.ll_cust_phone:
                bundle.putString("type", "khdh");
                UIHelper.showSimpleBackForResult(this, mActivity, 0, SimpleBackPage.CUST_PHEON, bundle, "客服电话");
                break;
            case R.id.ll_sale:
                bundle.putString("type", "ywy");
                UIHelper.showSimpleBackForResult(this, mActivity, 4, SimpleBackPage.CUST_PHEON, bundle, "业务员");
                break;
            case R.id.ll_fh_warehouse:
                bundle.putString("type", "fhck");
                UIHelper.showSimpleBackForResult(this, mActivity, 5, SimpleBackPage.CUST_PHEON, bundle, "发货仓库");
                break;
            case R.id.ll_date:
                new SlideDateTimePicker.Builder(getFragmentManager())
                        .setListener(listener)
                        .setInitialDate(new Date())
                        .build()
                        .show();
                break;
        }
    }

    private SlideDateTimeListener listener = new SlideDateTimeListener() {

        @Override
        public void onDateTimeSet(Date date) {
            String str = StringUtils.getDateString(date);
            tvDate.setText(str);
            head.setDate(str);
        }

        @Override
        public void onDateTimeCancel() {
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
            if (item != null) {
                String name = item.getName();
                String id = item.getId();
                switch (requestCode) {
                    case 0:
                        tvCustPhone.setText(name);
                        head.setKfdhName(name);
                        head.setKfdhId(id);
//                        MatHeadManager2.getInstance(mActivity).inOrRe(HeadBean);
                        break;
                    case 1:
                        tvGhUnit.setText(name);
                        head.setGhdwName(name);
                        head.setGhdwId(id);
//                        MatHeadManager2.getInstance(mActivity).inOrRe(HeadBean);
                        break;
                    case 2:
                        tvSalesWay.setText(name);
                        head.setXsfsName(name);
                        head.setXsfsId(id);
//                        MatHeadManager2.getInstance(mActivity).inOrRe(HeadBean);
                        break;
                    case 3:
                        tvPgnoType.setText(name);
                        head.setSklxName(name);
                        head.setSklxId(id);
//                        MatHeadManager2.getInstance(mActivity).inOrRe(HeadBean);
                        break;
                    case 4:
                        tvSale.setText(name);
                        head.setYwyName(name);
                        head.setYwyId(id);
//                        MatHeadManager2.getInstance(mActivity).inOrRe(HeadBean);
                        break;
                    case 5:
                        tvFhWarehouse.setText(name);
                        head.setFhckName(name);
                        head.setFhckId(id);
//                        ArrayList<BackMatBean> backList1 = mAdapter.getBackList();
//                        for (int i = 0; i < backList1.size(); i++) {
//                            backList1.get(i).setFDCStockID(id);
//                            backList1.get(i).setFDCStockName(name);
//                        }
//                        mAdapter.setBackList(backList1);
//                        mAdapter.notifyDataSetChanged();
                        break;
                    case 6:
                        tvPgno.setText(name);
                        head.setHybName(name);
                        head.setHybId(id);
//                        MatHeadManager2.getInstance(mActivity).inOrRe(HeadBean);
                        break;
                    case 7://adapter中点击发货仓库 自选的仓库
                        ArrayList<BackMatBean> backList = mAdapter.getBackList();
                        BackMatBean backMatBean = backList.get(position);
                        backMatBean.setTDCStockID(item.getId());
                        backMatBean.setTDCStockName(item.getName());
                        backList.set(position, backMatBean);
                        mAdapter.setBackList(backList);
                        mAdapter.notifyItemChanged(position);
                        break;

                }
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_add_mat, menu);
        if ("show".equals(mType)) {
            MenuItem item = menu.getItem(0);
            item.setVisible(false);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                subMat();
                break;
            case R.id.btn_save:
                saveMat();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void saveMat() {
        ArrayList<BackMatBean> backList = mAdapter.getBackList();
        if (backList != null && backList.size() > 0) {
            String fhckId = head.getFhckId();
            String ghdwId = head.getGhdwId();
            String hybId = head.getHybId();
            String kfdhId = head.getKfdhId();
            String sklxId = head.getSklxId();
            String xsfsId = head.getXsfsId();
            String ywyId = head.getYwyId();
            head.setDesc(tvBz.getText().toString().trim());

//            if (!StringUtils.isEmpty(fhckId) && !StringUtils.isEmpty(ghdwId) && !StringUtils.isEmpty(kfdhId) && !StringUtils.isEmpty(sklxId) &&
//                    !StringUtils.isEmpty(xsfsId) && !StringUtils.isEmpty(ywyId)) {
            head.setFtype("3");//2代表销售出库，3代表退货
            head.setUserName(AppContext.getInstance().getCurrentUser().getName());
            MatHeadManager2.getInstance(mActivity).inOrRe(head);
            MatHead lastHead = MatHeadManager2.getInstance(mActivity).getLastHead();
            for (int i = 0; i < backList.size(); i++) {
                backList.get(i).setHead(lastHead);
            }
            BackMatManager.getInstance(mActivity).insertBackMats(backList);
            Snackbar.make(mActivity.getWindow().getDecorView(), "保存成功!", Snackbar.LENGTH_SHORT).show();
            isSave = true;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mActivity.finish();
                    Bundle bundle = new Bundle();
                    UIHelper.showSimpleBack(mActivity, SimpleBackPage.ADD_BACK_MAT, bundle, "退货");
                }
            }, 1000);//3秒后执行Runnable中的run方法

//            } else {
//                Snackbar.make(mActivity.getWindow().getDecorView(), "必填信息不能为空!", Snackbar.LENGTH_SHORT).show();
//            }
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "未扫描单据不能保存!", Snackbar.LENGTH_SHORT).show();
        }


    }

    private void subMat() {

        ArrayList<BackMatBean> allMats = mAdapter.getBackList();
        if (allMats == null || allMats.size() == 0) {
            Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描物料，再提交", Snackbar.LENGTH_SHORT).show();
            return;
        }

        String fhckId = head.getFhckId();
        String ghdwId = head.getGhdwId();
        String hybId = head.getHybId();
        String kfdhId = head.getKfdhId();
        String sklxId = head.getSklxId();
        String xsfsId = head.getXsfsId();
        String ywyId = head.getYwyId();
        String date = head.getDate();


        if (!StringUtils.isEmpty(fhckId) && !StringUtils.isEmpty(ghdwId) && !StringUtils.isEmpty(kfdhId) && !StringUtils.isEmpty(sklxId) &&
                !StringUtils.isEmpty(xsfsId) && !StringUtils.isEmpty(ywyId)) {

            if (!StringUtils.isToday(date)) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "请修改提交日期！", Snackbar.LENGTH_SHORT).show();
                return;
            }


            MatSubBean.TableHead tableHead = new MatSubBean.TableHead();

            tableHead.setFDate(date);
            tableHead.setFCusPhone(kfdhId);
            tableHead.setFDCStockID(fhckId);
//            head.setFExplanation(etPaper);
            tableHead.setFEmpID(ywyId);
//            tableHead.setFRealReceive(etMoney);
            tableHead.setFSaleStyle(xsfsId);
            tableHead.setFStockDept(hybId);
            tableHead.setFSupplyID(ghdwId);
            tableHead.setFReceiveType(sklxId);
            tableHead.setFtype("-1");
            tableHead.setFExplanation(tvBz.getText().toString().trim() + "");


            List<MatSubBean.TableBody> bodys = new ArrayList<>();
            for (int i = 0; i < allMats.size(); i++) {
                BackMatBean count1 = allMats.get(i);
                MatSubBean.TableBody body = new MatSubBean.TableBody();
                String count = count1.getCount();
                double saleprice = 0;
                if ("0".equals(count1.getUnitType())) {//0代表baseName 1代表unit_name
                    saleprice = count1.getReprice();
                    body.setFUnitId(count1.getBaseunit());
                } else if ("1".equals(count1.getUnitType())) {
                    saleprice = count1.getSaleprice();
                    body.setFUnitId(count1.getUnit_id());
                }
                double v = Double.parseDouble(count);
                double Amount = ArithUtil.round((v * saleprice), 0);

//                if ("0".equals(count1.getUnitType())) {//0代表baseName 1代表unit_name
//                    body.setFUnitId(count1.getBaseunit());
//                } else if ("1".equals(count1.getUnitType())) {
//                    body.setFUnitId(count1.getUnit_id());
//                }

                body.setFProductID(count1.getId());
                body.setFSaleAmount("" + -Amount);
//                body.setFSalePrice(count1.getSaleprice() + "");
                body.setFSalePrice(saleprice + "");
                String count2 = count1.getCount();
                if (count2.contains(".")) {
                    String cou = count2.substring(0, count2.indexOf("."));
                    int i1 = Integer.parseInt(cou);
                    body.setFQty("" + -i1);
                } else {
                    body.setFQty("" + -Integer.parseInt(count2));
                }

                String value = MatHeadManager.getInstance(mActivity).getIDByName("发货仓库", "3");

                String tdcStockID = count1.getTDCStockID();
//                String cusvalue = count1.getFDCStockID();
                if (!StringUtils.isEmpty(tdcStockID)) {
                    body.setFStockId(tdcStockID);
                } else if (!StringUtils.isEmpty(value)) {
                    body.setFStockId(value);
                } else {
                    body.setFStockId("0");
                }
                bodys.add(body);
            }

            showWaitDialog();
            MatSubBean matSubBean = new MatSubBean();
            matSubBean.setBodyList(bodys);
            matSubBean.setHeadDetaili(tableHead);
            Gson gson = new Gson();
            String json = gson.toJson(matSubBean);
            PLog.i("lj", json);
            String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
            CM cm = new CM();
            cm.setToken(token);
            cm.setData(json);
            RetrofitSingleton.getApiService(mActivity).
                    StockBillSubmit(cm)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "必填信息不能为空！", Snackbar.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }

    @Override
    public void onFHCKClick(BackMatBean bean, int position) {
        this.position = position;
        Bundle bundle = new Bundle();
        bundle.putString("type", "fhck");
        UIHelper.showSimpleBackForResult(this, mActivity, 7, SimpleBackPage.CUST_PHEON, bundle, "发货仓库");
    }

    @Override
    public void onDwClick(final BackMatBean Bean, TextView tvUnit, final int position) {
//        final String[] strings = {Bean.getBaseName(), Bean.getUnit_name()};
//        DialogHelp.getSingleChoiceDialog(mActivity, "单位", strings, 0, new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialogInterface, int i) {
//                Bean.setUnitType(i + "");
//                dialogInterface.dismiss();
//                mAdapter.notifyItemChanged(position);
//            }
//        }).show();
    }

    @Override
    public void onMoneyChanged() {
        ArrayList<BackMatBean> backList = mAdapter.getBackList();
        double allMoney = 0;
        for (BackMatBean bean : backList) {
            allMoney = ArithUtil.add(allMoney, bean.getAllMoney());
        }
        double round = ArithUtil.round(allMoney, 0);
        tvAllMoney.setText(round + "");

    }

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "提交成功!", Snackbar.LENGTH_SHORT).show();
                if ("show".equals(mType) || isSave) {
                    MatHeadManager2.getInstance(mActivity).delAllById(head.getId());
                    BackMatManager.getInstance(mActivity).delAllByHeadId(head.getId());//提交成功后删除缓存
                }
                mActivity.finish();
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };

}
